package cn.summit.captcha.service;

import cn.summit.captcha.config.CaptchaProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @author summit
 * @since 2020/8/19 21:58
 */
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CaptchaCodeCreator {

    private final CaptchaProperties captchaProperties;

    private final Random random = new Random(System.currentTimeMillis());

    private final Font font;

    public CaptchaCodeCreator(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
        font = new Font("楷体", Font.BOLD, captchaProperties.getHeight() - 4);
    }

    /**
     * 获取颜色
     *
     * @param fc 最小
     * @param bc 最大
     * @return 颜色
     */
    private Color getRandomColor(int fc, int bc) {

        fc = Math.min(fc, 255);
        bc = Math.min(bc, 255);

        int r = fc + random.nextInt(bc - fc - 16);
        int g = fc + random.nextInt(bc - fc - 14);
        int b = fc + random.nextInt(bc - fc - 12);

        return new Color(r, g, b);
    }

    private int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    public String getResponseImage(OutputStream os) throws IOException {
        String code = this.generateCaptchaCode(captchaProperties.getCaptchaSize(),
            captchaProperties.getVerifyCodes());
        outputImage(captchaProperties.getWidth(), captchaProperties.getHeight(), os, code);
        return code;
    }

    private Color getRandomColor1(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    public void  outputImage(int w, int h, OutputStream os, String code) throws IOException {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandomColor1(200, 250);
        // 设置背景色
        g2.setColor(Color.white);
        g2.fillRect(0, 2, w, h - 4);

        // 绘制干扰线
        addLine(w, h, g2);

        // 添加噪点
        addNoise(w, h, image);

        // 使图片扭曲
        shear(g2, w, h, c);

        // 画验证码
        addCaptchaCode(w, h, code, g2);

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    /**
     * 画验证码code
     *
     * @param w 宽
     * @param h 高
     * @param code 验证码
     * @param g2 Graphics2D
     */
    private void addCaptchaCode(int w, int h, String code, Graphics2D g2) {
        int verifySize = code.length();
        int fontSize = h - 4;

        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            g2.setColor(getRandomColor1(108, 190));

            AffineTransform affine = new AffineTransform();
            affine
                .setToRotation(Math.PI / 4 * random.nextDouble() * (random.nextBoolean() ? 1 : -1),
                    (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 5);
        }
    }

    /**
     * 绘制干扰线
     *
     * @param w 宽
     * @param h 高
     * @param g2 Graphics2D对象
     */
    private void addLine(int w, int h, Graphics2D g2) {
        g2.setColor(getRandomColor1(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }
    }

    /**
     * 添加噪点
     *
     * @param w 宽
     * @param h 高
     * @param image 图片
     */
    private void addNoise(int w, int h, BufferedImage image) {
        // 噪声率
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }
    }


    private void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1) * Math.sin((double) i / (double) period
                + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1) * Math.sin((double) i / (double) period
                + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }

    public String generateCaptchaCode(int verifySize, String sources) {
        int codesLen = sources.length();
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(random.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

}
